package com.maximus.cli;

import com.maximus.cli.system.SystemEnvironment;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.ThreadContext;
import org.apache.logging.log4j.spi.ThreadContextMap;
import org.jline.reader.LineReader;
import org.jline.reader.LineReaderBuilder;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;

public class CliMain {
    private static final Logger logger = LogManager.getLogger(CliMain.class);

    public static void main(String[] args) throws IOException {
        logger.info("cli 启动");

        String fileName = "/commands.json";
        URL url = CliMain.class.getResource(fileName);

        // 检查资源是否存在
        if (url == null) {
            throw new FileNotFoundException("File not found in classpath: " + fileName);
        }

        ThreadContext.put("baseUrl", "/Users/maximusyoung/Documents/logs/JavaRedis");
        //windows系统 /D:/ideaProject/JavaRedis/JavaRedisCli/target/classes/commands.json
        //mac /Users/maximusyoung/Documents/GitHub/JavaRedis/java-redis/JavaRedisCli/target/classes/commands.json
        //处理路径时需要区分系统
        logger.info("path:" + url.getPath());
        String path = "";

        String os = System.getProperty("os.name").toLowerCase();
        if (os.contains("win")) {
            path = url.getPath().substring(1);
        } else if (os.contains("mac")) {
            path = url.getPath();
        } else {
            path = url.getPath();
        }
        SystemEnvironment.initCommands(path);

        try (Terminal terminal = TerminalBuilder.terminal()) {
            terminal.enterRawMode();

            LineReader lineReader = LineReaderBuilder.builder()
                .terminal(terminal)
                .build();

            while (true) {
                String a = lineReader.readLine("JavaRedis Cli > ");
                int c = terminal.reader().read(16);
                if (c >= 0) {
                    terminal.writer().write(c);
                    terminal.writer().flush();

                    // Use "q" to quit early
                    if (c == 81 || c == 113) break;
                } else {
                    if (c == -1) break; // Got EOF
                }
            }
        }

    }
}